package me.yuzho.study.concurrency;

import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import static net.mindview.util.Print.*;

/** 阻塞线程方法1：通过调用sleep方法来使线程进入休眠状态,可中断的阻塞
 * @author yzhou-citrix
 *
 */
class SleepBlocked implements Runnable {
    public void run() {
        
        try {
            TimeUnit.SECONDS.sleep(100);
        } catch (InterruptedException e) {
            //e.printStackTrace();
            print("InterruptedException ...");
        }
      
        print("Exiting SleepBlocked.run()");
    }
}

/** 阻塞线程方法2：等待输入输出, 不可中断的阻塞
 * @author yzhou-citrix
 *
 */
class IOBlocked implements Runnable {
    
    private InputStream in;
    
    public IOBlocked(InputStream is) {
        in = is;
    }

    @Override
    public void run() {
        
        try {
            print("Waiting for read(): ");
            in.read();
        } catch (IOException e) {
            if(Thread.currentThread().isInterrupted()) {
                print("Interrupted from bocked I/O");
            } else {
                throw new RuntimeException();
            }
        }
        
        print("Exiting IOBlocked.run()");
    }
    
}

/** 阻塞方法3： 试图调用同步控制方法，但对象锁不可用，另一个任务已经获取了这个锁，不可中断的阻塞
 * @author yzhou-citrix
 *
 */
class SynchronizedBlocked implements Runnable {
    public synchronized void f() {
        while(true) { // Never rleases lock
            Thread.yield();
        }
    }
    
    public SynchronizedBlocked() {
        new Thread() {
            public void run() {
                f(); // lock acquired by this interal thread
            }
        }.start();
    }

    @Override
    public void run() {
        print("Trying to call f(), but it could not be run due to no lock could be acquired");
        
        f();
        
        print("Exiting SynchronizedBlocked.run()");
    }
}

/**  展示线程interrupt方法的的基本用法
 * @author yzhou-citrix
 *
 */
public class Interrupting {

    private static ExecutorService exec = Executors.newCachedThreadPool();
    
    static void test(Runnable r) throws InterruptedException {
        Future<?> f = exec.submit(r);
        TimeUnit.MILLISECONDS.sleep(100);
        print("Interrupting " + r.getClass().getName());
        
        f.cancel(true);// 使用Executor 执行的线程调用f.cancel()相当于调用thread的interrupt
        
        print("Interrupt sent to " + r.getClass().getName());
    }
    
    public static void main(String[] args) throws Exception {
        test(new SleepBlocked());
        test(new IOBlocked(System.in));
        test(new SynchronizedBlocked());
        
        TimeUnit.SECONDS.sleep(3);
        
        print("Aborting with System.exit(0)");
        
        System.exit(0);// ... since last 2 interrupts failed
    }
    
}
